Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

While Loop

While examples

Basic while loop to count from 1 to 10:

Basic while loop to count from 1 to 10
public class Main{ public static void main(String[] args){ int i = 1; while (i <= 10) { System.out.println(i); i++; } } }

Output

1 2 3 4 5 6 7 8 9 10
This Java program uses a while loop to count from 1 to 10 and prints each number in the sequence. Here's how it works: Initialize an integer variable i with an initial value of 1. This variable will be used to keep track of the current number in the sequence. Enter a while loop with the condition while (i <= 10). This loop will continue to execute as long as i is less than or equal to 10. Inside the loop, the program uses System.out.println() to print the current value of i, which represents the number in the sequence. After printing the number, the program increments i by 1 using i++. This moves the loop to the next number in the sequence. The loop continues to iterate until i becomes greater than 10, at which point the loop terminates.

Summing numbers using a while loop:

Summing numbers using a while loop
public class Main{ public static void main(String[] args){ int sum = 0; int i = 1; while (i <= 5) { sum += i; i++; } System.out.println("Sum of numbers from 1 to 5: " + sum); } }

Output

Sum of numbers from 1 to 5: 15
This Java program calculates the sum of numbers from 1 to 5 using a while loop. Here's how it works: Initialize two integer variables: sum is set to 0. This variable will store the sum of the numbers i is set to 1. This variable is used to iterate through the numbers from 1 to 5. Enter a while loop with the condition while (i <= 5). This loop will continue to execute as long as i is less than or equal to 5. Inside the loop, the program adds the current value of i to the sum variable using sum += i. This step accumulates the sum of the numbers. After adding i to sum, the program increments i by 1 using i++. This moves the loop to the next number in the sequence. The loop continues to iterate until i becomes greater than 5, at which point the loop terminates. After the loop exits, the program prints the calculated sum of numbers from 1 to 5 using System.out.println().

While loop to iterate through an array

While loop to iterate an array
public class Main{ public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; int index = 0; while (index < numbers.length) { System.out.println(numbers[index]); index++; } } }

Output

1 2 3 4 5
This Java program demonstrates how to use a while loop to iterate through an array of integers and print each element. Here's how it works: Define an integer array named numbers containing the values {1, 2, 3, 4, 5}. This is the array that you want to iterate through and print its elements. Initialize an integer variable named index with an initial value of 0. This variable will be used to keep track of the current index in the array. Enter a while loop with the condition while (index < numbers.length). This loop will continue to execute as long as the index is less than the length of the numbers array. Inside the loop, the program uses System.out.println() to print the element at the current index in the numbers array, which is numbers[index]. After printing the element, the program increments the index by 1 using index++, which moves the loop to the next index in the array. The loop continues to iterate until the index reaches the length of the numbers array, at which point the loop terminates.

While loop with a boolean condition:

While loop with a boolean condition
public class Main{ public static void main(String[] args){ boolean isRunning = true; while (isRunning) { System.out.println("The loop is running."); isRunning = false; // Set to false to exit the loop. } } }

Output

The loop is running.
This Java while program demonstrates the use of a while loop with a boolean condition to control the loop's execution. Here's how it works: It initializes a boolean variable isRunning and sets it to true. This variable acts as the loop control condition. It enters a while loop with the condition while (isRunning). This means that the loop will continue executing as long as isRunning is true. Inside the loop, it prints the message "The loop is running." After printing the message, it sets the isRunning variable to false. This effectively changes the loop control condition to false. Since the loop control condition is now false, the loop terminates, and the program continues with any code after the loop.

While loop to find the factorial of a number:

find the factorial of a number
public class Main{ public static void main(String[] args){ int num = 5; int factorial = 1; while (num > 0) { factorial *= num; num--; } System.out.println("Factorial of 5 is: " + factorial); } }

Output

Factorial of 5 is: 120
Initialize an integer variable num with the value 5. This is the number for which we want to calculate the factorial. Initialize an integer variable factorial with the initial value of 1. This variable will store the result of the factorial calculation. Enter a while loop with the condition while (num > 0). This loop will continue to execute as long as num is greater than 0. Inside the loop, the program multiplies the current value of factorial by the value of num and assigns the result back to factorial. This effectively calculates the factorial as factorial = factorial * num. After calculating the factorial for the current num value, the program decrements num by 1 using num--, moving closer to 0. The loop continues to iterate, repeatedly multiplying the factorial by the decreasing num until num becomes 0. After the loop exits, the program prints the calculated factorial of 5 using System.out.println().

Using a while loop to reverse a string:

While loop to reverse a string
public class Main{ public static void main(String[] args) { String str = "Hello, World!"; int length = str.length(); String reversed = ""; while (length > 0) { reversed += str.charAt(length - 1); length--; } System.out.println("Reversed string: " + reversed); } }

Output

Reversed string: !dlroW ,olleH
This example java program reverses a given string, "Hello, World!", using a while loop. Here's how the program works: Initialize a String variable named str with the value "Hello, World!". This is the string we want to reverse. Calculate the length of the str string using the str.length() method and store it in an integer variable named length. Initialize an empty string variable named reversed to store the reversed string. Enter a while loop with the condition while (length > 0). This loop will continue to execute as long as the length variable is greater than zero. Inside the loop, the program appends the character at the length - 1 position of the str string to the reversed string using the str.charAt(length - 1) method. This effectively reverses the characters of the original string one by one. After appending the character, the program decrements the length variable by 1, moving towards the beginning of the string. The loop continues until it has processed all characters in the original string. Finally, outside the loop, the program prints the reversed string by concatenating it with the "Reversed string: " message and using System.out.println().

While loop to simulate a dice roll until a specific number is rolled:

While loop to simulate a dice roll
public class Main{ public static void main(String[] args) { Random random = new Random(); int targetNumber = 6; int roll; int attempts = 0; while ((roll = random.nextInt(6) + 1) != targetNumber) { System.out.println("Rolled a " + roll); attempts++; } System.out.println("It took " + attempts + " attempts to roll a " + targetNumber); } }

Output

Rolled a 3 Rolled a 5 Rolled a 2 Rolled a 6 It took 4 attempts to roll a 6
This Java program simulates rolling a six-sided dice until a specific target number (in this case, 6) is rolled. It also keeps track of the number of attempts it takes to roll the target number. Here's how the program works: Initialize a Random object named random to generate random numbers. Set the targetNumber to 6, which is the number we want to roll. Create an integer variable named roll to store the result of each dice roll. Initialize an integer variable named attempts to keep track of the number of attempts it takes to roll the target number. Enter a while loop with the condition (roll = random.nextInt(6) + 1) != targetNumber. This loop generates a random number between 1 and 6 (inclusive) using random.nextInt(6) + 1 and assigns it to the roll variable. It continues looping until the roll is equal to the targetNumber, which means the target number has been rolled. Inside the loop, it prints the result of each roll, indicating the number rolled with the message "Rolled a X," where X is the number rolled. It also increments the attempts counter by 1 for each roll. When the loop exits (i.e., the target number is rolled), it prints a message indicating the number of attempts it took to roll the target number.

While loop to print even numbers from 1 to 20:

While loop to print even numbers
public class Main{ public static void main(String[] args) { int number = 2; while (number <= 20) { System.out.println(number); number += 2; } } }

Output

2 4 6 8 10 12 14 16 18 20
This Java program prints even numbers from 2 to 20 using a while loop. Here's an explanation of how it works: Initialize an integer variable number with the value 2. This will be the starting point for our loop. Enter a while loop with the condition while (number <= 20). This loop will continue executing as long as the value of number is less than or equal to 20. Inside the loop, it prints the value of number using System.out.println(number). This statement displays the current value of number. Increment number by 2 using number += 2. This step ensures that number is updated to the next even number in each iteration. The loop continues until number becomes greater than 20.

Using a while loop to find the greatest common divisor (GCD) of two numbers:

(GCD) of two numbers example in java
public class Main{ public static void main(String[] args) { int a = 36; int b = 48; while (b != 0) { int temp = b; b = a % b; a = temp; } System.out.println("GCD of 36 and 48 is: " + a); } }

Output

GCD of 36 and 48 is: 12
Initialize two integer variables a and b with the values 36 and 48, respectively. These are the two numbers for which we want to find the GCD. Enter a while loop with the condition while (b != 0). This loop will continue executing as long as b is not equal to zero. Inside the loop, a temporary variable temp is created and assigned the value of b. This step is crucial because we need to update b in the next line while keeping its original value for further calculations. Update the value of b to be the remainder of the division of a by b, calculated as a % b. This operation replaces the value of b with the remainder of the division. Update the value of a with the value stored in the temp variable, which was the original value of b before the update. This step effectively swaps the values of a and b. The loop continues until b becomes zero. When b becomes zero, it means that the GCD has been found, and the loop terminates. Finally, outside the loop, the program prints the GCD of 36 and 48 using the value stored in variable a. These examples demonstrate different use cases of while loops in , from basic counting to more complex tasks.

  📌TAGS

★while ★while loop ★while syntax ★syntax ★ example

Tutorials